import os
import sys
import pandas as pd
import numpy as np

def setup_paths():
    """设置基础路径和数据路径"""
    BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))
    if BASE_DIR not in sys.path:
        sys.path.insert(0, BASE_DIR)

    # 创建结果目录
    result_dir = os.path.join(BASE_DIR, "data", "4_weighting_modeling", "weights_result")
    os.makedirs(result_dir, exist_ok=True)
    return BASE_DIR, result_dir

def calculate_weights(df, indicator_cols, selected_method):
    """计算指标权重"""
    if selected_method == 'pca':
        weights = pca_weight(df, indicator_cols)
    elif selected_method == 'entropy':
        weights = entropy_weight(df, indicator_cols)
    elif selected_method == 'independence':
        weights = independence_weight(df, indicator_cols)
    elif selected_method == 'combine':
        entropy_w = entropy_weight(df, indicator_cols)
        independence_w = independence_weight(df, indicator_cols)
        weights = combine_entropy_and_independence_weights(entropy_w, independence_w)
    else:
        raise ValueError(f"无效的权重计算方法: {selected_method}")
    
    weights_df = pd.DataFrame({
        'Indicator': weights.index,
        'Weight': weights.values,
        'Method': selected_method
    })
    
    weight_file = os.path.join(result_dir, f"indicator_weights_{selected_method}.csv")
    weights_df.to_csv(weight_file, index=False, encoding='utf-8-sig')
    
    return weights

def process_evaluation(df_level, level_weights, selected_method, eval_choice, result_dir):
    """处理评价方法"""
    if eval_choice == '1':
        output_path = os.path.join(result_dir, f"RSR_评分排序_{selected_method}.csv")
        result_df = rsr_ranking(df_level.copy(), level_weights, output_path, num_levels=4)
    elif eval_choice == '2':
        output_path = os.path.join(result_dir, f"TOPSIS_评分排序_{selected_method}.csv")
        result_df = topsis_ranking(df_level.copy(), level_weights, output_path, num_levels=4)
    else:
        raise ValueError(f"无效的评价方法: {eval_choice}")
    
    # 存储原始结果
    result_path = output_path
    print(f"✅ {eval_choice} 排序结果已保存为: {result_path}")
    
    return result_df, result_path

def attach_country_attributes(result_df, result_path, data_dir):
    """将国家属性附加到排序结果"""
    attach_country_attributes(result_df, result_path, data_dir)
    print("🌍 已附加国家属性信息")

def main():
    """主函数: 程序入口点"""
    # 设置路径
    BASE_DIR, result_dir = setup_paths()
    
    # 加载数据
    data_dir = os.path.join(BASE_DIR, "data", "4_weighting_modeling")
    input_file = os.path.join(data_dir, "indicators_binned_dynamic_quantile.csv")
    df = pd.read_csv(input_file)
    
    # 定义元数据列
    meta_cols = ['序号', '国名En', '国名Ch', '年份']
    indicator_cols = [col for col in df.columns if col not in meta_cols]
    
    # 权值计算方法选择
    print("\n === 权值计算方法选择 === ")
    methods = {
        '1': ('PCA 主成分分析法', 'pca'),
        '2': ('熵权法 Entropy', 'entropy'),
        '3': ('独立性权重法 Independence', 'independence'),
        '4': ('综合权重法 Combine', 'combine')
    }
    
    print("请选择权值计算方法:")
    for key, (name, _) in methods.items():
        print(f"{key}: {name}")
    
    while True:
        weight_choice = input("输入对应数字(1-4)选择方法: ").strip()
        if weight_choice in methods:
            selected_method = methods[weight_choice][1]
            method_name = methods[weight_choice][0]
            break
        else:
            print("❌ 无效选择，请重新输入!")

    # 计算并保存权重
    weights = calculate_weights(df, indicator_cols, selected_method)
    
    # 计算一级指标得分和权重
    df_level, level_weights = generate_level_scores(df, weights, meta_cols, result_dir, selected_method)
    print("📊 一级指标加权得分和权重计算完成")
    
    # 评价方法选择
    print("\n === 评价方法选择 === ")
    print("1: RSR")
    print("2: TOPSIS")
    
    while True:
        eval_choice = input("请选择评价方法: ").strip()
        if eval_choice in ['1', '2']:
            break
        print("❌ 无效选择，请重新输入!")
    
    # 执行评价方法并附加国家属性
    result_df, result_path = process_evaluation(df_level, level_weights, selected_method, eval_choice, result_dir)
    attach_country_attributes(result_df, result_path, data_dir)

if __name__ == "__main__":
    main()


